package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.uuid.IdUtils;
import com.ecnu.system.domain.*;
import com.ecnu.system.domain.dto.ProjectPlanDTO;
import com.ecnu.system.domain.vo.ProjectListVO;
import com.ecnu.system.domain.vo.ProjectPlanVO;
import com.ecnu.system.domain.vo.UserVO;
import com.ecnu.system.mapper.*;
import com.ecnu.system.service.IProjectPlanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * ecnu_活动_计划表 服务实现类
 * </p>
 *
 * @author zdn
 * @since 2025-03-24
 */
@Service
public class ProjectPlanServiceImpl extends ServiceImpl<ProjectPlanMapper, ProjectPlan> implements IProjectPlanService {
    @Autowired
    private ProjectPlanMapper projectPlanMapper;
    @Autowired
    private ProjectTeacherMapper teacherMapper;
    @Autowired
    private ProjectUserMapper userMapper;
    @Autowired
    private ProjectStageUserMapper stageUserMapper;
    @Autowired
    private ProjectMapper projectMapper;


    /**
     * 分页查询
     */
    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    protected String getId() {
        return IdUtils.fastSimpleUUID();
    }

    protected String getUuId() {
        return IdUtils.fastUUID();
    }

    @Override
    public TableDataInfo getList(ProjectPlanDTO dto, LoginUser loginUser) {
        try {
            Project project = projectMapper.selectOne(new QueryWrapper<Project>().eq("id", dto.getId()));
            if (project == null) {
                return OtherUtil.tableError("项目不存在");
            }

            //添加限制，不是教师，不是超管的只能见自己参与的任务
            Long userId = null;
            LambdaQueryWrapper<ProjectTeacher> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProjectTeacher::getProId, dto.getId());
            wrapper.eq(ProjectTeacher::getTechId, loginUser.getUserId());
            List<ProjectTeacher> projectTeachers = teacherMapper.selectList(wrapper);
            boolean isUnauthorizedRole = loginUser.getUser().getRoles().stream()
                    .noneMatch(role -> role.getRoleId() != 1L && role.getRoleId()!=2L);
            if (!isUnauthorizedRole) {
                if ((projectTeachers == null || projectTeachers.isEmpty())
                        &&!project.getCreateUser().equals(String.valueOf(loginUser.getUserId()))
                ) {
                    userId = loginUser.getUserId();
                }
            }
            //获取可见的任务
            startPage(dto.getPageDomain());
            List<ProjectPlan> projectPlans = projectPlanMapper.selectLists(dto, userId);
            TableDataInfo dataInfo = OtherUtil.tableSuccess(projectPlans);
            List<ProjectPlanVO> vos = OtherUtil.copy(dataInfo.getRows(), ProjectPlanVO.class);
            //人员处理，状态处理
            if (!vos.isEmpty()) {
                //1、负责人获取逻辑--计划编号
                List<String> fileList = vos.stream()
                        .map(ProjectPlanVO::getId)
                        .collect(Collectors.toList());
                //取信息
                List<UserVO> teachers = teacherMapper.selectByPlanId(fileList);
                Map<String, List<UserVO>> teachMap = teachers.stream()
                        .collect(Collectors.groupingBy(UserVO::getProId));

                //2、相关人员逻辑--参与人员ID
                //取信息
                List<UserVO> users = userMapper.selectByPlanId(fileList);
                Map<String, List<UserVO>> userMap = users.stream()
                        .collect(Collectors.groupingBy(UserVO::getProId));
                //根据ID写入人员信息
                vos.forEach(a -> {
                    List<UserVO> userList = userMap.get(a.getId());
                    a.setUserList(userList == null ? new ArrayList<>() : userList);
                    List<UserVO> teacherList = teachMap.get(a.getId());
                    a.setTeacherList(teacherList == null ? new ArrayList<>() : teacherList);
                });
            }
            dataInfo.setRows(vos);
            return dataInfo;
        } catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException
                e) {
            log.error("查询失败：" + e.getMessage());
            TableDataInfo error = OtherUtil.tableError(e.getMessage());
            return error;
        }
    }

    @Override
    public boolean del(String[] ids) {
        for (String id : ids) {
            ProjectPlan plan = new ProjectPlan();
            plan.setMissionId(id);
            int i = projectPlanMapper.updateByMissionId(plan);
        }
        return true;
    }

    @Override
    public AjaxResult info(String id) {
        QueryWrapper<ProjectPlan> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        wrapper.eq("del_flag", "0");
        ProjectPlan projectPlan = projectPlanMapper.selectOne(wrapper);
        if (projectPlan == null) {
            return AjaxResult.success(new ProjectListVO());
        }
        ProjectPlanVO vo = new ProjectPlanVO();
        BeanUtils.copyProperties(projectPlan, vo);
        //1、负责人获取逻辑--计划编号
        List<String> fileList = new ArrayList<>();
        fileList.add(projectPlan.getId());
        //取信息
        List<UserVO> teachers = teacherMapper.selectByPlanId(fileList);

        //2、相关人员逻辑--参与人员ID
        //取信息
        List<UserVO> users = userMapper.selectByPlanId(fileList);
        //根据ID写入人员信息
        vo.setUserList(users == null ? new ArrayList<>() : users);
        vo.setTeacherList(teachers == null ? new ArrayList<>() : teachers);
        return AjaxResult.success(vo);
    }

    @Override
    public AjaxResult edit(ProjectPlanVO dto) {
        if (dto.getStartTime() == null || dto.getEndTime() == null) {
            return AjaxResult.error("开始时间和结束时间不能为空");
        }

        // 可选：时间先后顺序校验
        if (dto.getStartTime().after(dto.getEndTime())) {
            return AjaxResult.error("开始时间不能晚于结束时间");
        }
        if (StringUtils.isBlank(dto.getId())) {
            ProjectPlan plan = new ProjectPlan();
            BeanUtils.copyProperties(dto, plan);
            plan.setId(getUuId());
//            plan.setStartTime(OtherUtil.getEndOfDay(dto.getStartTime()));
            plan.setEndTime(OtherUtil.getEndOfDay(dto.getEndTime()));
            boolean save = save(plan);
            if (!save) {
                return AjaxResult.error("保存失败");
            }
            if (dto.getTeacherList() != null) {
                extractedTeach(dto.getTeacherList(), plan.getId());
            }
            if (dto.getUserList() != null) {
                extractedUser(dto.getUserList(), plan);//记得改user表名称
            }

            return AjaxResult.success("保存成功", plan.getId());
        } else {
            ProjectPlan plan = new ProjectPlan();
            BeanUtils.copyProperties(dto, plan);
//            plan.setId(getUuId());
//            plan.setStartTime(OtherUtil.getEndOfDay(dto.getStartTime()));
            plan.setEndTime(OtherUtil.getEndOfDay(dto.getEndTime()));
            boolean save = updateById(plan);
            if (!save) {
                return AjaxResult.error("保存失败");
            }
            if (dto.getTeacherList() != null) {
                //后续需要调整表名
                extractedTeach(dto.getTeacherList(), plan.getId());
            }
            if (dto.getUserList() != null) {
                extractedUser(dto.getUserList(), plan);//记得改user表名称
            }
            return AjaxResult.success("保存成功", plan.getId());
        }
    }

    //负责人
    private void extractedTeach(List<UserVO> dto, String planId) {

        //删除（改状态）
        teacherMapper.updateByPlanId(planId);
        if (!dto.isEmpty()) {

            teacherMapper.insertBatch(dto.stream()
                    .map(user -> {
                        ProjectTeacher teacher = new ProjectTeacher();
                        teacher.setId(getUuId());
                        teacher.setProId(planId);
                        teacher.setTeachName(user.getUsername());
                        teacher.setTechId(user.getId());
                        return teacher;
                    })
                    .collect(Collectors.toList()));
        }
    }

    //相关成员
    private void extractedUser(List<UserVO> dto, ProjectPlan planId) {

        stageUserMapper.deleteByFileId(planId.getId());
        if (!dto.isEmpty()) {
            stageUserMapper.insertBatch(dto.stream()
                    .map(user -> {
                        ProjectStageUser stageUser = new ProjectStageUser();
                        stageUser.setId(getUuId());
                        stageUser.setMissionId(planId.getId());
                        stageUser.setUserId(user.getId());
                        stageUser.setUserName(user.getUsername());
                        stageUser.setProId(planId.getProId());
                        return stageUser;
                    })
                    .collect(Collectors.toList()));
        }
    }
}
